﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using Newtonsoft.Json;
using System.Text;
using System.Net;
using System.IO;
using log4net;
using System.Data;
using MRO.ClientApplication.Util;
using MRO.ClientApplication.ModelsDto.Response;
using MRO.ClientApplication.Models.BaiYa;
using System.Web.Http;
using MRO.ClientApplication.BaseClient;
using System.Net.Http;
using Ma.Bussiness.ConfigExtend;

namespace MRO.ClientApplication.AppService.BaiYaApi
{
    public class BaiYaAppService
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(BaiYaAppService));

        /// <summary>
        /// 百亚生成订单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public BYCreateProcessResponse CreateProcess(BYCreateProcess request)
        {
            try
            {
                return BaiYaClient.PostWithToken<BYCreateProcessResponse>(StaticField.BaiYa_CreateWorkflowPost, request);
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        /// <summary>
        /// 获取出库类型
        /// </summary>
        /// <returns></returns>
        public static List<BaiYa_KeyValue> GetQtcklxList()
        {
            return CacheHelper.GetOrSetCache("QtcklxList", () =>
            {
                var QtckList = BaiYaClient.PostWithToken<List<BaiYa_KeyValue>>(StaticField.BaiYa_cklxPost);
                return QtckList.Where(x => x.Number == "五金备件领料" || x.Number == "内部领用出库" || x.Number.StartsWith("6098") || x.Number == "固定资产领料").ToList();
            });
        }

        /// <summary>
        /// 获取研发项目类型
        /// </summary>
        /// <returns></returns>
        public static List<BaiYa_KeyValue> GetYfxmList()
        {
            return CacheHelper.GetOrSetCache("YfxmList", () =>
            {
                return BaiYaClient.PostWithToken<List<BaiYa_KeyValue>>(StaticField.BaiYa_YfxmPost);
            });
        }

        /// <summary>
        /// 获取在建工程项目类型
        /// </summary>
        /// <returns></returns>
        public static List<BaiYa_KeyValue> GetZjgcList()
        {
            return CacheHelper.GetOrSetCache("ZjgcList", () =>
            {
                return BaiYaClient.PostWithToken<List<BaiYa_KeyValue>>(StaticField.BaiYa_ZjgcPost);
            });
        }

        /// <summary>
        /// 获取机台号
        /// </summary>
        /// <returns></returns>
        public static List<BaiYa_NumberName> GetDepartment()
        {
            return CacheHelper.GetOrSetCache("departmentlist", () =>
            {
                var param = new BaiYa_DepartmentRequest
                {
                    Number = StaticField.BaiYa_Number,
                    NumberStart = StaticField.BaiYa_NumberStart
                };
                return BaiYaClient.PostWithToken<List<BaiYa_NumberName>>(StaticField.BaiYa_ZjgcPost, param);
            });
        }

        /// <summary>
        /// 查询人员详细信息
        /// </summary>
        /// <param name="people"></param>
        /// <returns></returns>
        public static BaiYa_People GetPeople(string people)
        {
            try
            {
                var param = new BaiYa_PeopleRequest { UserNumber = people.Substring(0, 7) };
                var res = BaiYaClient.PostWithToken<List<BaiYa_People>>(StaticField.BaiYa_PeopleApi, param);
                return res.FirstOrDefault();
            }
            catch (HttpRequestException httpEx)
            {
                logger.Error("HTTP Request Error: " + httpEx.Message, httpEx);
                throw new Exception("HTTP request error occurred.");
            }
            catch (Exception ex)
            {
                logger.Error("General Error: " + ex.Message, ex);
                throw new Exception("An error occurred while retrieving people data.");
            }
        }

        /// <summary>
        /// 百亚 采购申请单
        /// </summary>
        /// <param name="purchase"></param>
        /// <returns></returns>
        public static PurchaseResult SendPurchase(BaiYa_Purchase param)
        {
            try
            {
                return BaiYaClient.PostWithToken<PurchaseResult>(StaticField.BaiYa_PurchaseApi, param);
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        /// <summary>
        /// 获取出库结果
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static BaiYa_Result GetOutStockApi(BaiYa_LingLiao param)
        {
            try
            {
                BaiYaClient.PostWithToken<PurchaseResult>(StaticField.BaiYa_OutStockApi, param);
                return BaiYaClient.PostWithToken<BaiYa_Result>(StaticField.BaiYa_PurchaseApi, param);
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message}");
            }
        }

        public string GetCustMarCode(string code)
        {
            string sql = $"SELECT def1 FROM bd_custmaterial where code='{code}'";
            //return Connection.T6.ExecuteScalar(sql)?.ToString() ?? "~";
            return "~";
            ;
        }
        public static string DataSource(string outno)
        {
            return $@"
                    SELECT row_number() over (order by cSOCode) seq, a.*,c.mobile,o.intro cdes
                    FROM {StaticField.BaiYa_PurchaseApi }.dbo.v_mro_lingliao_BY a
                    LEFT JOIN {StaticField.BaiYa_PurchaseApi}.dbo.bd_stordoc b ON a.cWhName=b.name
                    LEFT JOIN dbo.njboso_user c ON a.cDefine13=c.realname
                    LEFT JOIN dbo.njboso_goods_order o ON a.cSOCode=o.oid
                    WHERE a.outno='{outno}'";
        }

        public static bool CheckSendPurchase(bool resMail)
        {
            var sendList = BY_DeliveryLog_repo.GetList().Where(x => string.IsNullOrEmpty(x.BYInNo) && x.iscalculatedinvcost.Contains("Y")).ToList();
            var BYsql = "SELECT * FROM BYStockTypes";
            //var mrodb = Connection.MRO;
            //var byStockTypeList = mrodb.GetList<BYStockType>(BYsql);
            var byStockTypeList=new List<BYStockType>();
            foreach (var item in sendList)
            {
                try
                {
                    var check = BY_DeliveryLog_repo.GetObject(item.OutNo);
                    if (!string.IsNullOrEmpty(check.BYInNo)) continue;

                    //var resDt = mrodb.ExecuteQuery(DataSource(item.OutNo));
                    var resDt = new DataTable();
                    var cWhName = resDt.Rows[0]["cWhName"].ToString();
                    var stockCode = byStockTypeList.FirstOrDefault(a => a.WarehouseName == cWhName)?.WarehouseCodeBy;
                    if (string.IsNullOrEmpty(stockCode))
                    {
                        throw new Exception($"仓库'{cWhName}'对应的百亚仓库不存在");
                    }

                    var purchase = new BaiYa_Purchase
                    {
                        Fdate = DateTime.Now.ToString("yyyy-MM-dd"),
                        OrgCode = "BYG01",
                        SqUserCode = resDt.Rows[0]["cDefine13"].ToString().Substring(0, 7),
                        Note = resDt.Rows[0]["cdes"].ToString(),
                        OutBillNo = item.OutNo,
                        Details = resDt.AsEnumerable().Select(row => new BaiYa_PurchaseDetail
                        {
                            SupplierCode = StaticField.BaiYa_SuppNo,
                            CinvCode = row["cInvAddCode"].ToString().Trim(),
                            CinvName = row["cInvName"].ToString(),
                            StockCode = stockCode,
                            Qty = Convert.ToInt32(row["iQuantity"].ToString()),
                            PurchaseOrgCode = "BYG01",
                            RequestOrgCode = "BYG01",
                            Oalcid = row["pr_po"].ToString()
                        }).ToList()
                    };

                    var pres = SendPurchase(purchase);
                    item.BYInNo = string.IsNullOrEmpty(pres.BillNo) ? "" : pres.BillNo;
                    item.BYInTime = DateTime.Now;
                    BY_DeliveryLog_repo.Update(item);
                }
                catch (Exception ex)
                {
                    logger.Error(item.OutNo + "发送百亚采购申请单运行异常：" + ex.Message);
                    resMail = false;
                }
            }
            return resMail;
        }

        //public static CarryoverList DoPurchase(CarryoverList apply)
        //{
        //    try
        //    {
        //        var data = GetPurchase(apply);
        //        var res = SendPurchase(data);
        //        apply.CustomerOutBillNo = res.BillNo ?? "";
        //        return apply;
        //    }
        //    catch (HttpRequestException httpEx)
        //    {
        //        logger.Error("HTTP Request Error: " + httpEx.Message, httpEx);
        //        throw new Exception("HTTP request error occurred.");
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error("Error in DoPurchase: " + ex.Message, ex);
        //        throw new Exception("An error occurred while processing the purchase.");
        //    }
        //}

        ///// <summary>
        ///// 获取百亚 采购物料信息
        ///// </summary>
        ///// <param name="apply"></param>
        ///// <returns></returns>
        //public static BaiYa_Purchase GetPurchase(CarryoverList apply)
        //{
        //    try
        //    {
        //        var purchaseList = new BaiYa_Purchase
        //        {
        //            Fdate = DateTime.Now.ToString("yyyy-MM-dd"),
        //            OrgCode = "BYG01",
        //            SqUserCode = apply.ApplyName,
        //            Note = "",
        //            Transfer = true,
        //            OutBillNo = apply.OutBillNo,
        //            Details = new List<BaiYa_PurchaseDetail>()
        //        };

        //        using (var imro = new ImroDbcontext())
        //        {
        //            foreach (var item in apply.CarryoverListBodies)
        //            {
        //                var shelfInfo = imro.ShelfInfos.FirstOrDefault(x => x.CustomerSku == item.CinvAddCode);
        //                var stockCode = imro.BYStockTypes.FirstOrDefault(x => x.WarehouseName == shelfInfo.WareHouseName)?.WarehouseCodeBy;

        //                if (string.IsNullOrEmpty(stockCode))
        //                {
        //                    throw new Exception($"{shelfInfo.WareHouseName} 对应的百亚仓库编号不存在");
        //                }

        //                var detail = new BaiYa_PurchaseDetail
        //                {
        //                    SupplierCode = StaticField.BaiYa_SuppNo,
        //                    CinvCode = item.CinvAddCode,
        //                    CinvName = shelfInfo.MaterialName,
        //                    StockCode = stockCode,
        //                    UnitCode = "",
        //                    Qty = item.Num,
        //                    Note = "", //备注
        //                    PurchaseOrgCode = "BYG01",
        //                    RequestOrgCode = "BYG01",
        //                    PriceUnit = "",
        //                    StockUnit = "",
        //                    Oalcid = item.Pr_Po
        //                };

        //                purchaseList.Details.Add(detail);
        //            }
        //        }

        //        return purchaseList;
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error("Error in GetPurchase: " + ex.Message, ex);
        //        throw new Exception("An error occurred while getting purchase data.");
        //    }
        //}

        ///// <summary>
        ///// 发送百亚领料记录
        ///// </summary>
        //public static bool SendIntro(bool resMail)
        //{
        //    var sendList = BY_DeliveryLog_repo.GetList().Where(x => string.IsNullOrWhiteSpace(x.BYOutNo)).ToList();
        //    var mrodb = Connection.MRO;
        //    var byStockTypeList = mrodb.GetList<BYStockType>("SELECT * FROM BYStockTypes");
        //    while (sendList.Any())
        //    {
        //        var info = sendList.FirstOrDefault();
        //        sendList.Remove(info);

        //        try
        //        {
        //            logger.Info($"{info.OutNo} -- 开始发送百亚领料记录 -->");
        //            var check = BY_DeliveryLog_repo.GetObject(info.OutNo);

        //            if (!string.IsNullOrEmpty(check.BYOutNo) || string.IsNullOrWhiteSpace(info.BYInNo) && info.iscalculatedinvcost == "Y")
        //            {
        //                continue;
        //            }

        //            var resDt = mrodb.ExecuteQuery(DataSource(info.OutNo));
        //            var peopleRes = GetPeople(resDt.Rows[0]["cDefine13"].ToString());

        //            var lingLiao = new BaiYa_LingLiao
        //            {
        //                Fdate = DateTime.Now.ToString("yyyy-MM-dd"),
        //                StockOrgNo = "BYG01",
        //                ReceiveOrgNo = "BYG01",
        //                StockDirect = "GENERAL",
        //                ReceiveDeptNo = peopleRes.OrgNumber,
        //                ReceivePeopleNo = resDt.Rows[0]["cDefine13"].ToString().Substring(0, 7),
        //                SuppNo = StaticField.BaiYa_SuppNo,
        //                UserDeptNo = peopleRes.OrgNumber,
        //                Yfxm = mrodb.GetRow($"SELECT top 1 * FROM BY_Return_Order WHERE oid='{resDt.Rows[0]["cSOCode"]}'")["yfxm"].ToString(),
        //                Zjgcxm = mrodb.GetRow($"SELECT top 1 * FROM BY_Return_Order WHERE oid='{resDt.Rows[0]["cSOCode"]}'")["zjgc"].ToString(),
        //                CkStatus = mrodb.GetRow($"SELECT top 1 * FROM BY_Return_Order WHERE oid='{resDt.Rows[0]["cSOCode"]}'")["cklx"].ToString(),
        //                OutBillNo = info.OutNo,
        //                Details = new List<LingLiao_Detail>()
        //            };


        //            var stockCode = byStockTypeList.FirstOrDefault(a => a.WarehouseName == resDt.Rows[0]["cWhName"].ToString())?.WarehouseCodeBy;

        //            if (string.IsNullOrEmpty(stockCode))
        //            {
        //                throw new Exception($"仓库'{resDt.Rows[0]["cWhName"]}'对应的百亚仓库不存在");
        //            }

        //            for (int j = 0; j < resDt.Rows.Count; j++)
        //            {
        //                var detail = new LingLiao_Detail
        //                {
        //                    Cinvcode = resDt.Rows[j]["cInvAddCode"].ToString().Trim(),
        //                    RealQty = Math.Round(Convert.ToDecimal(resDt.Rows[j]["iQuantity"].ToString()), 4),
        //                    OrgNo = "BYG01",
        //                    StockNo = stockCode,
        //                    StockStatus = "KCZT01_SYS",
        //                    Oalcid = resDt.Rows[j]["pr_po"].ToString()
        //                };

        //                lingLiao.Details.Add(detail);
        //            }

        //            var outresOne = GetOutStockApi(lingLiao);
        //            resMail = resMail && outresOne.Result.ResponseStatus.IsSuccess;

        //            if (outresOne.Result.ResponseStatus.IsSuccess)
        //            {
        //                info.BYOutNo = outresOne.Result.Number;
        //                info.BYOutTime = DateTime.Now;
        //                BY_DeliveryLog_repo.Update(info);
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            logger.Error($"{info.OutNo} 发送百亚领料异常：" + ex.Message);
        //            resMail = false;
        //        }
        //    }

        //    return resMail;
        //}

    }

}